
package com.startx.core.netty.output.http;

import java.io.UnsupportedEncodingException;

import com.startx.core.system.constants.Headers;
import com.startx.core.tools.JsonTool;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

/**
 * keepalive
 */
public class Keepalive {

	/**
	 * 返回http状态
	 * @param ctx
	 * @param status
	 */
	public static void status(ChannelHandlerContext ctx, HttpResponseStatus status) {
		FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
		setPublicHeader(res);
		ctx.channel().writeAndFlush(res);
	}

	/**
	 * 返回Object，默认转为json
	 * 
	 * @param ctx
	 * @param status
	 * @param result
	 * @throws UnsupportedEncodingException
	 */
	public static void object(ChannelHandlerContext ctx, HttpResponseStatus status, Object result)
			throws UnsupportedEncodingException {
		ByteBuf buffer = Unpooled.wrappedBuffer(JsonTool.obj2json(result).getBytes("utf-8"));
		FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buffer);
		setPublicHeader(res);
		ctx.channel().writeAndFlush(res);
		
	}

	/**
	 * 返回字节数组
	 * 
	 * @param ctx
	 * @param status
	 * @param data
	 */
	public static void bytes(ChannelHandlerContext ctx, HttpResponseStatus status, byte[] data) {
		ByteBuf buffer = Unpooled.wrappedBuffer(data);
		FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buffer);
		setPublicHeader(res);
		ctx.channel().writeAndFlush(res);
	}

	/**
	 * 返回字符串
	 * 
	 * @param ctx
	 * @param status
	 * @param result
	 */
	public static void string(ChannelHandlerContext ctx, HttpResponseStatus status, String result)
			throws UnsupportedEncodingException {
		ByteBuf buffer = Unpooled.wrappedBuffer(result.getBytes("utf-8"));
		FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buffer);
		setPublicHeader(res);
		ctx.channel().writeAndFlush(res);
	}

	/**
	 * 返回htt报文
	 */
	public static void http(ChannelHandlerContext ctx, FullHttpResponse res) {
		setPublicHeader(res);
		ctx.channel().writeAndFlush(res);
	}

	/**
	 * 设置公共header
	 * @param res
	 */
	private static void setPublicHeader(FullHttpResponse res) {
		res.headers().add(Headers.getJsonHeader());
		res.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
		res.headers().set(HttpHeaderNames.CONTENT_LENGTH, res.content().readableBytes());
	}

}
